<?php

class Album_m extends CI_Model {
   
	function create_album_batch($data){
		return 
		$this->db->insert_batch('album', $data);
		echo $this->db->last_query();die;
	}
	
	function create_album($filename = ''){		
		$userdata = $this->session->userdata('userdata');
		if($userdata){
			//update ngay_cap_nhat
			$this->db->where('id', $userdata['canhan_id']);
			date_default_timezone_set('Asia/Bangkok');
			$this->db->update('canhan', array('ngay_cap_nhat'=>date('Y-m-d H:i:s')));
			$data = array(
				'canhan_id'		=>	$userdata['canhan_id'],
				'thumb'			=> $filename				
			);
			$this->db->insert('album', $data);			
			//echo $this->db->last_query();die;
			return $this->db->insert_id();
		}
		return false;
	}
	
	function update_avatar($filename){
		$userdata = $this->session->userdata('userdata');
		if($userdata){
			$data = array(
				'user_id'		=>	$userdata['id'],
				'avatar'			=> $filename				
			);
			$this->db->where('user_id', $userdata['id']);
			if($userdata['loai'] == 1)
				return $this->db->update('canhan', $data);	
			else if($userdata['loai'] == 2)
				return $this->db->update('nhatuyendung', $data);	
		}
		return false;
	}
	
	function update_album($data){
		//echo '<pre>';print_r($data);die;
		$userdata = $this->session->userdata('userdata');
		if($userdata){
			$not_in = array();
			foreach($data as $obj)
				$not_in[]	= $obj['id'];
			$this->db->where_not_in('id', $not_in);
			$this->db->where('canhan_id',$userdata['canhan_id']);
			$this->db->delete('album');
			#echo $this->db->last_query();die;
			//update ngay_cap_nhat
			$this->db->where('id', $userdata['canhan_id']);
			date_default_timezone_set('Asia/Bangkok');
			$this->db->update('canhan', array('ngay_cap_nhat'=>date('Y-m-d H:i:s')));
		}
		return 
		$this->db->update_batch('album', $data, 'id');
		echo $this->db->last_query();die;
	}
	
	function get_album(){
		$userdata = $this->session->userdata('userdata');
		if($userdata){
			$this->db->select('a.*');
			$this->db->from('users u');
			$this->db->join('canhan cn', 'cn.user_id=u.id');
			$this->db->join('album a', 'a.canhan_id=cn.id');
			$this->db->where('a.trang_thai', 1);
			$this->db->where('u.id', $userdata['id']);
			$this->db->order_by('a.thu_tu', 'ASC');
			return 
			$this->db->get()->result();
		}
		return false;
	}
	
	function get_album_by_canhan_id($canhan_id){
			$this->db->select('a.*');
			$this->db->from('canhan cn');
			$this->db->join('album a', 'a.canhan_id=cn.id');
			$this->db->where('a.trang_thai', 1);
			$this->db->where('cn.id', $canhan_id);
			$this->db->order_by('a.thu_tu', 'ASC');
			return 
			$this->db->get()->result();
	}
}
